package com.hup.minicontroller.common.netty.handler;

import android.util.Log;

import com.hup.minicontroller.common.netty.NettyConstant;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 解决粘包问题的处理器,帧数据格式详见 {@link DataCodecHandler}
 *
 * @author hugan
 * @date 2021/4/25
 */
//@Sharable//框架限制本类不能设置成共享单例
public class DataSplitter extends LengthFieldBasedFrameDecoder {
    private static final String TAG = DataSplitter.class.getSimpleName();

    public DataSplitter() {
        super(Integer.MAX_VALUE, NettyConstant.FRAME_LENGTH_FIELD_OFFSET, NettyConstant.FRAME_LENGTH_FIELD_SIZE);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        // 屏蔽(收到的)非本协议的数据
        int head = in.getInt(in.readerIndex());
        if (head != NettyConstant.FRAME_HEAD) {
            Log.w(TAG, "decode: 帧头异常:head=" + head);
            //ctx.channel().close();//不能关闭!? 数据会在网络不好/丢包时发生?
            return null;
        }
        return super.decode(ctx, in);//下一个处理器继续处理
    }
}
